<template>
  <div class="research-page">
    <div class="table-container">
      <h3 class="table-title">{{ whitePaperName || '调研任务执行列表' }}</h3>
      
      <div class="table-loading" v-if="isLoading">
        <el-loading-spinner class="el-icon-loading" style="font-size: 28px; color: #1E60FA;"></el-loading-spinner>
        <p class="loading-text">正在加载调研任务...</p>
      </div>

      <el-table
        ref="tableRef"
        :data="researchList"
        style="width: 100%"
        size="small"
        :border="false"
        :header-cell-style="{ background: '#fff', fontWeight: 'normal', color: '#ACB9CD' }"
        :row-style="{ borderBottom: '1px solid #e4e7ed' }"
        empty-text="暂无调研任务"
        :max-height="tableMaxHeight"
        v-else
      >
        <el-table-column prop="id" label="编号" width="140" />
        <el-table-column prop="chapterName" label="章节" width="180" />
        <el-table-column prop="title" label="标题" width="150" />
        <el-table-column prop="taskName" label="任务名称" width="160"/>
        <el-table-column prop="status" label="状态" width="110">
          <template #default="scope">
            <el-tag 
              type="primary" 
              style="--el-tag-text-color: #165dff; --el-tag-bg-color: rgba(22, 93, 255, 0.1);"
            >
              {{ scope.row.status || '待启动' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="surveyResultNum" 
          label="调研结果" 
          width="110"
          :formatter="formatSurveyResult"
        />
        <el-table-column prop="analyseResult" label="分析结果" width="110" />
        <el-table-column label="操作" width="110">
          <template #default="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleConfigChange(scope.row.id)"
              style="background: #165dff; border-color: #165dff;"
              :disabled="!validProjectId"
            >
              更改配置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { taskList, startTask } from '@/api/whitepaper/myproject'

export default {
  name: "ResearchAnalysis",
  props: {
    formData: { type: Object, default: () => ({}) },
    projectId: { type: [Number, String], default: 0 },
    whitePaperName: { type: String, default: '' }
  },
  data() {
  return {
    researchList: [],
    isLoading: true, // 初始加载状态
    retryCount: 0,
    maxRetry: 3,
    retryInterval: 3000,
    windowHeight: 0,
    bottomBarHeight: 80,
    headerHeight: 0,
    isTaskLoading: false,
    hasInitiatedLoad: false,
    retryTimer: null,
    delayTimer: null
  };
},
  computed: {
  validProjectId() {
    const propsId = Number(this.projectId);
    if (!isNaN(propsId) && propsId > 0) {
      console.log('validProjectId：从props获取', propsId);
      return propsId;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const urlProjectId = Number(urlParams.get('projectId'));
    if (!isNaN(urlProjectId) && urlProjectId > 0) {
      console.log('validProjectId：从路由projectId获取', urlProjectId);
      return urlProjectId;
    }

    const urlId = Number(urlParams.get('id'));
    if (!isNaN(urlId) && urlId > 0) {
      console.log('validProjectId：从路由id获取', urlId);
      return urlId;
    }

    console.log('validProjectId：无效，返回0');
    return 0;
  },
  isActiveStep() {
    const result = Number(this.$route.query.step) === 3;
    console.log('isActiveStep：', result, '路由step：', this.$route.query.step);
    return result;
  },
  tableMaxHeight() {
    // 根据屏幕高度动态调整表格高度
    const baseHeight = this.windowHeight - this.headerHeight - this.bottomBarHeight - 80;
    
    if (this.windowHeight <= 900) {
      return Math.max(baseHeight, 300);
    } else if (this.windowHeight <= 1080) {
      return Math.max(baseHeight, 400);
    } else {
      return Math.max(baseHeight, 500);
    }
  }
},

  activated() {
  console.log('ResearchAnalysis激活：', {
    validProjectId: this.validProjectId,
    hasInitiatedLoad: this.hasInitiatedLoad
  });
  this.isLoading = true;
  this.initHeight();
  
  // 清除之前的定时器
  if (this.delayTimer) {
    clearTimeout(this.delayTimer);
  }
  
  // 延迟2秒后触发加载
  this.delayTimer = setTimeout(() => {
    this.triggerLoadTaskList();
  }, 2000);
},
  mounted() {
  console.log('ResearchAnalysis挂载：');
  this.initHeight();
  window.addEventListener('resize', this.handleResize);
  
  // 清除之前的定时器
  if (this.delayTimer) {
    clearTimeout(this.delayTimer);
  }
  
  // 延迟2秒后触发加载
  this.delayTimer = setTimeout(() => {
    this.triggerLoadTaskList();
  }, 2000);
},

// 修改 deactivated 方法
deactivated() {
  window.removeEventListener('resize', this.handleResize);
  this.isLoading = false;
  this.isTaskLoading = false;
  this.hasInitiatedLoad = false;
  clearTimeout(this.retryTimer);
  // 清除延迟定时器
  if (this.delayTimer) {
    clearTimeout(this.delayTimer);
    this.delayTimer = null;
  }
  console.log('ResearchAnalysis失活：重置状态');
},

  beforeDestroy() {
  window.removeEventListener('resize', this.handleResize);
  clearTimeout(this.retryTimer);
  // 清除延迟定时器
  if (this.delayTimer) {
    clearTimeout(this.delayTimer);
    this.delayTimer = null;
  }
},
  methods: {
    triggerLoadTaskList() {
  if (this.validProjectId > 0 && !this.hasInitiatedLoad && !this.isTaskLoading) {
    console.log('触发加载任务列表：调用initTaskList');
    this.retryCount = 0;
    this.initTaskList(true);
  } else {
    console.log('不触发加载任务列表：', {
      validProjectId: this.validProjectId > 0,
      hasInitiatedLoad: !this.hasInitiatedLoad,
      isTaskLoading: !this.isTaskLoading
    });
    this.isLoading = false;
  }
},
    initHeight() {
  this.windowHeight = window.innerHeight;
  const headerSection = document.querySelector('.header-section');
  const progressSection = document.querySelector('.progress-section');
  const pageTitle = document.querySelector('.table-title');
  this.headerHeight = 
    (headerSection?.offsetHeight || 0) +
    (progressSection?.offsetHeight || 0) +
    (pageTitle?.offsetHeight || 0) +
    20;
  
  // 笔记本屏幕检测
  console.log('屏幕高度:', this.windowHeight, '类型:', this.getScreenType());
},

// 新增屏幕类型检测方法
getScreenType() {
  const height = this.windowHeight;
  if (height <= 768) return 'small';
  if (height <= 900) return 'medium';
  if (height <= 1080) return 'large';
  return 'xlarge';
},
    handleResize() {
      this.initHeight();
      this.$nextTick(() => {
        this.$refs.tableRef?.doLayout();
      });
    },
    async initTaskList(allowRetry = false) {
  const projectId = this.validProjectId;
  console.log('initTaskList执行：', { projectId, allowRetry, retryCount: this.retryCount });

  // 前置校验：项目ID无效，直接关闭加载
  if (projectId <= 0) {
    this.researchList = [];
    this.isLoading = false;
    this.isTaskLoading = false;
    this.$message.warning('项目ID无效，无法加载调研任务');
    console.log('initTaskList：项目ID无效，终止');
    return;
  }

  // 前置校验：正在请求或已加载过，终止
  if (this.isTaskLoading || this.hasInitiatedLoad) {
    console.log('initTaskList：正在请求或已加载，终止');
    return;
  }

  this.isTaskLoading = true; // 上锁
  try {
    console.log('调用taskList接口：', { projectId });
    const res = await taskList({ projectId });
    console.log('taskList接口返回：', res);

    const responseData = res.data || res;
    const successCodes = [200, 0];

    if (successCodes.includes(responseData.code || res.code)) {
      // 处理返回数据
      this.researchList = Array.isArray(responseData.data) 
        ? responseData.data 
        : Array.isArray(responseData) 
          ? responseData 
          : [];
      console.log('调研任务列表数据：', this.researchList);

      this.hasInitiatedLoad = true; 
      this.isLoading = false;
      this.retryCount = 0;
      clearTimeout(this.retryTimer);
      console.log('加载完成：', this.researchList.length > 0 ? '有数据' : '无数据');
    } else {
      // 接口返回失败（非200状态），保留重试逻辑
      this.researchList = [];
      this.hasInitiatedLoad = true;
      const errorMsg = responseData.msg || '调研任务请求失败';
      
      if (allowRetry && this.retryCount < this.maxRetry) {
        this.retryCount++;
        this.$message.warning(`${errorMsg}，正在重试（${this.retryCount}/${this.maxRetry}）`);
        this.retryTimer = setTimeout(() => {
          this.initTaskList(allowRetry);
        }, this.retryInterval);
      } else {
        this.isLoading = false;
        this.$message.error(errorMsg);
        clearTimeout(this.retryTimer);
      }
      console.log('接口返回失败：', errorMsg);
    }
  } catch (err) {
    // 接口调用异常（网络错误等），保留重试逻辑
    this.researchList = [];
    this.hasInitiatedLoad = true;
    const errorMsg = err.message || '调研任务加载失败';
    console.error('taskList接口调用异常：', err);
    
    if (allowRetry && this.retryCount < this.maxRetry) {
      this.retryCount++;
      this.$message.warning(`${errorMsg}，正在重试（${this.retryCount}/${this.maxRetry}）`);
      this.retryTimer = setTimeout(() => {
        this.initTaskList(allowRetry);
      }, this.retryInterval);
    } else {
      this.isLoading = false;
      this.$message.error(`${errorMsg}，请刷新页面重试`);
      clearTimeout(this.retryTimer);
    }
  } finally {
    this.isTaskLoading = false; // 解锁
    console.log('initTaskList执行结束：', { isLoading: this.isLoading });
  }
},
    formatSurveyResult(row) {
      return row.surveyResultNum ? `${row.surveyResultNum}条` : '0条';
    },
    handleConfigChange(taskId) {
      const projectId = this.validProjectId;
      if (projectId <= 0) {
        this.$message.error("未获取到有效项目ID，无法执行操作");
        return;
      }
      this.$router.push({
        path: '/whitepaper/form',
        query: { 
          step: 0, 
          projectId: projectId,
          from: 'configChange',
          timestamp: new Date().getTime()
        }
      });
    },
    validate(callback) {
      callback(true);
    }
  }
};
</script>

<style scoped>
.research-page {
  padding: 0 20px;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.table-container {
  margin-bottom: 20px;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 重要：防止flex内容溢出 */
}
.table-title {
  font-size: 16px;
  color: #0C1124;
  margin-bottom: 10px;
  font-weight: 700;
  height: 40px;
  line-height: 40px;
  flex-shrink: 0; /* 防止标题被压缩 */
}
.el-table::before {
  display: none !important;
}
::v-deep .el-table {
  --el-table-border-color: transparent;
  --el-table-row-hover-bg-color: #f5f7fa;
  height: 100%;
  flex: 1;
}
::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
  min-height: 200px;
  max-height: 100%;
}
::v-deep .el-table__body-wrapper tr td {
  border-bottom: 1px solid #e4e7ed;
}
::v-deep .el-button--mini {
  padding: 4px 12px;
}
/* 滚动条样式优化 */
::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ccc;
}
::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: transparent;
}
::v-deep .el-tag--primary {
  border: none !important;
}

/* 表格局部加载样式（居中显示转圈） */
.table-loading {
  width: 100%;
  height: 400px; /* 固定高度，避免占用过多空间 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  position: relative;
  flex-shrink: 0;
}
.loading-text {
  margin-top: 20px;
  font-size: 15px;
  color: #1E60FA;
  font-weight: 400;
}
/* 局部加载转圈动画优化 */
::v-deep .table-loading .el-loading-spinner {
  animation: rotate 1.5s linear infinite !important;
}

/* 笔记本屏幕适配 */
@media (max-width: 1440px) {
  .research-page {
    padding: 0 15px;
  }
  
  .table-loading {
    height: 350px; /* 笔记本屏幕下减小高度 */
  }
  
  .table-title {
    font-size: 15px;
    height: 36px;
    line-height: 36px;
    margin-bottom: 8px;
  }
  
  ::v-deep .el-table {
    font-size: 13px;
  }
  
  ::v-deep .el-table__body-wrapper {
    min-height: 180px;
  }
}

@media (max-width: 1366px) {
  .research-page {
    padding: 0 12px;
  }
  
  .table-loading {
    height: 320px;
  }
  
  .table-title {
    font-size: 14px;
    height: 34px;
    line-height: 34px;
  }
  
  ::v-deep .el-table {
    font-size: 12px;
  }
  
  ::v-deep .el-button--mini {
    padding: 3px 10px;
    font-size: 12px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 1280px) {
  .research-page {
    padding: 0 10px;
  }
  
  .table-loading {
    height: 300px;
  }
  
  .loading-text {
    font-size: 14px;
    margin-top: 15px;
  }
  
  ::v-deep .table-loading .el-loading-spinner {
    font-size: 24px !important;
  }
}

/* 表格列宽适配小屏幕 */
@media (max-width: 1440px) {
  ::v-deep .el-table .el-table__cell {
    padding: 8px 0;
  }
  
  ::v-deep .el-table .el-table__cell:nth-child(1) { width: 120px; } /* 编号 */
  ::v-deep .el-table .el-table__cell:nth-child(2) { width: 160px; } /* 章节 */
  ::v-deep .el-table .el-table__cell:nth-child(3) { width: 130px; } /* 标题 */
  ::v-deep .el-table .el-table__cell:nth-child(4) { width: 140px; } /* 任务名称 */
  ::v-deep .el-table .el-table__cell:nth-child(5) { width: 100px; } /* 状态 */
  ::v-deep .el-table .el-table__cell:nth-child(6) { width: 100px; } /* 调研结果 */
  ::v-deep .el-table .el-table__cell:nth-child(7) { width: 100px; } /* 分析结果 */
  ::v-deep .el-table .el-table__cell:nth-child(8) { width: 100px; } /* 操作 */
}

@media (max-width: 1366px) {
  ::v-deep .el-table .el-table__cell:nth-child(1) { width: 100px; }
  ::v-deep .el-table .el-table__cell:nth-child(2) { width: 140px; }
  ::v-deep .el-table .el-table__cell:nth-child(3) { width: 120px; }
  ::v-deep .el-table .el-table__cell:nth-child(4) { width: 130px; }
  ::v-deep .el-table .el-table__cell:nth-child(5) { width: 90px; }
  ::v-deep .el-table .el-table__cell:nth-child(6) { width: 90px; }
  ::v-deep .el-table .el-table__cell:nth-child(7) { width: 90px; }
  ::v-deep .el-table .el-table__cell:nth-child(8) { width: 90px; }
}

/* 超小屏幕文字省略 */
@media (max-width: 1280px) {
  ::v-deep .el-table .el-table__cell .cell {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>